<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\DictionaryData;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\Request;
use think\response\Json;

class Dictionary extends BaseController
{
    protected Model $model;
    public function initialize(): void
    {
        $this->model = new \app\model\Dictionary();
    }
    /**
     * 显示资源列表
     * @param Request $request
     * @return Json
     */
    public function index(Request $request) :Json
    {
        $payload = $request->get();
        if (!isset($payload['enterprise_id'])){
            return $this->result(400, '无法获取您的企业标识，请创建或是加入企业');
        }
        try {
            $data = $this->model->where('enterprise_id', $payload['enterprise_id'])
                ->select()->toArray();
            return $this->result(200, 'success', $data);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->result($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     * @param Request $request
     * @return Json
     */
    public function save(Request $request): Json
    {
        $data = $request->post();
        try {
            $item = $this->model->where('name', $data['name'])->count();
            if ($item) {
                return $this->result(400, '字典名称重复');
            } else {
                $this->model->create($data);
                return $this->result(200, '字典添加成功');
            }
        }catch (Exception $e){
            return $this->result($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param int $id
     * @return Json
     */
    public function update(Request $request, int $id): Json
    {
        $data = $request->put();
        try {
            $item = $this->model->where('name', $data['name'])->where('id', '<>', $id)->count();
            if ($item) {
                return $this->result(400, '字典名称重复');
            }
            $this->model->where('id', $id)->update($data);
            return $this->result(200, '字典更新成功');
        }catch( Exception $e){
            return $this->result($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Json
     */
    public function delete(int $id): Json
    {
        //删除字典
        try {
            $isData = (new DictionaryData())->where('dictionary_id', $id)->count();
            if ($isData){
                return $this->result(400, '请先删除字典数据');
            }
            $this->model->where('id', $id)->delete();
            return $this->result(200, '字典删除成功');
        }catch (Exception $e){
            return $this->result($e->getCode(), $e->getMessage());
        }
    }
}
